package com.ln.cmsln.service.impl.hu;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ln.cmsln.mapper.hu.CompanyProfileMapper;
import com.ln.cmsln.pojo.entity.hu.CompanyProfile;
import com.ln.cmsln.pojo.entity.hu.Curriculum;
import com.ln.cmsln.service.hu.CompanyProfileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Helen
 * @since 2022-03-31
 */
@Service
public class CompanyProfileServiceImpl extends ServiceImpl<CompanyProfileMapper, CompanyProfile> implements CompanyProfileService {


    @Override
    public boolean add(CompanyProfile companyProfile, String realPath, MultipartFile file) {
        try {
            String src = "src\\main\\resources\\image\\" + file.getOriginalFilename();
            //存入数据库图片路径
            companyProfile.setCImage(src);

            src = realPath+"\\"+src;

            File file1 = new File(src);
            if (!file1.exists()) {
                //mkdirs() 创建此抽象路径名指定的目录
                file1.mkdirs();
            }
            file.transferTo(file1);

            return baseMapper.insert(companyProfile) > 0;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateById(CompanyProfile companyProfile, String realPath, MultipartFile file) {
        if (companyProfile!=null){
            //查询出资讯信息
            CompanyProfile companyProfile1 = baseMapper.selectById(companyProfile.getCImage());
            if (companyProfile1!=null){
                //获取图片相对路径
                String imgUrl = companyProfile1.getCImage();
                File file1 = new File(realPath+imgUrl);
                //删除图片
                file1.delete();
            }
            try {
                //按照时间分组存储图片
                SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd/HH/mm");
                String format = df.format(new Date());
                //组装图片存储的路径
                String imagesUrl = "\\src\\main\\resources\\image\\"+format+"\\"+file.getOriginalFilename();
                realPath=realPath+imagesUrl;
                File file2 = new File(realPath);

                //没有该路径则创建
                if (!file2.exists()){
                    file2.mkdirs();
                }
                //写入文件
                file.transferTo(file2);
                //修改图片路径
                companyProfile.setCImage(imagesUrl);
            } catch (Exception e){
                e.printStackTrace();
                return false;
            }
        }
        return baseMapper.updateById(companyProfile) > 0;
    }
}
